package com.gaogzhen.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.enums.ApiErrorCode;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.gaogzhen.domain.SysMenu;
import com.gaogzhen.feign.OAuth2FeignClient;
import com.gaogzhen.service.SysLoginService;
import com.gaogzhen.service.SysMenuService;
import com.gaogzhen.utils.JwtToken;
import com.gaogzhen.utils.LoginResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 登录接口实现
 */
@Service
@Slf4j
public class SysLoginServiceImpl implements SysLoginService {

    @Autowired
    private OAuth2FeignClient oAuth2FeignClient;

    @Value("${basic.token:Basic Y29pbi1hcGk6Y29pbi1zZWNyZXQ=}")
    private String basicToken;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public LoginResult login(String username, String password) {
        log.info("用户-{}-开始登录", username);
        // 1、获取token,远程调用authorization-server服务
        ResponseEntity<JwtToken> tokenResponseEntity = oAuth2FeignClient.getToken("password", username, password, "admin_type", basicToken);
        if (tokenResponseEntity.getStatusCode() != HttpStatus.OK) {
            throw new ApiException(ApiErrorCode.FAILED);
        }
        JwtToken jwtToken = tokenResponseEntity.getBody();
        String token = jwtToken.getAccessToken();
        log.info("远程调用授权服务器成功，获取的token：{}", JSON.toJSONString(jwtToken, true));
        // 2、获取登录用户菜单列表
        // 2.1、解析token
        Jwt jwt = JwtHelper.decode(token);
        String jwtClaims = jwt.getClaims();
        JSONObject jwtJson = JSON.parseObject(jwtClaims);
        // 2.2、获取用户userId
        Long userId = Long.valueOf(jwtJson.getString("user_name"));
        List<SysMenu> menus = sysMenuService.getMenusByUserId(userId);
        // 3、获取登录用户的权限列表
        // 3.1、jwtToken中已经包含权限列表，直接获取
        JSONArray authorityArray = jwtJson.getJSONArray("authorities");
        List<SimpleGrantedAuthority> authorities = authorityArray.stream()
                .map(authorityJson -> new SimpleGrantedAuthority(authorityJson.toString()))
                .collect(Collectors.toList());
        // 4、把token存储在redis里面，配置我们的网关做jwt验证的操作
        redisTemplate.opsForValue().set(token,"", jwtToken.getExpiresIn() , TimeUnit.SECONDS);
        return new LoginResult(jwtToken.getTokenType() + " " + token, menus, authorities);
    }
}
